<template>
  <div>
    <yt-crud
      ref="crudRef"
      :data="data"
      :column="column"
      v-model:page="state.page"
      v-model:query="state.query"
      :total="state.total"
      :loading="state.loading"
      :tableProps="{
        selection: true,
        viewBtn: false,
        delBtn: false, // 设置为false，关闭默认删除按钮
        editBtn: false, // 设置为false，关闭默认修改按钮
        menuSlot: true, // 设置为true，开启自定义菜单按钮（仅保留详情功能）
        menuWidth: 120, // 减少宽度，因为只有一个按钮
        addBtn: false,
      }"
      :fun-props="{
        exportBtn: true,
        delBtn: false,
        addBtn: false,
      }"
      @openBeforeFun="openBeforeFun"
      @exportFun="handleExport"
      @onLoad="getData"
      @saveFun="onSave"
    >
      <template #menuSlot="scope">
        <el-tooltip class="box-item" effect="dark" content="详情" placement="top">
          <el-button link type="primary" :icon="View" @click="handleViewDetail(scope.row)" />
        </el-tooltip>
      </template>



      <template #collectTime="{ row }">{{ row.collectTime || '-' }}</template>
      <template #collectDatetime="{ row }">{{ formatDateWithMilliseconds(row.collectTime) }}</template>
    </yt-crud>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="state.detailDialog.visible"
      :title="state.detailDialog.title"
      width="900px"
      destroy-on-close
    >
      <el-descriptions v-if="state.detailDialog.data" :column="2" border>
        <el-descriptions-item label="ID">{{ state.detailDialog.data.id || '-' }}</el-descriptions-item>
        <el-descriptions-item label="租户ID">{{ state.detailDialog.data.tenantId || '-' }}</el-descriptions-item>
        <el-descriptions-item label="采集时间戳">{{ state.detailDialog.data.collectTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="采集时间">{{ formatDateWithMilliseconds(state.detailDialog.data.collectTime) }}</el-descriptions-item>
        <el-descriptions-item label="通道索引">{{ state.detailDialog.data.channelIndex || '-' }}</el-descriptions-item>
        
        <!-- 收集时间字符串 -->
        <el-descriptions-item label="收集时间字符串" :span="2">
          {{ state.detailDialog.data.collectDatetime || '-' }}
        </el-descriptions-item>
        
        <!-- 波长数据 -->
        <el-descriptions-item label="波长数据" :span="2">
          <div style="max-height: 300px; overflow-y: auto;">
            <el-row :gutter="16" style="margin-top: 10px;">
              <el-col :span="12" v-for="i in 30" :key="`wave-${i-1}`">
                <div style="display: flex; justify-content: space-between; padding: 4px 0;">
                  <span>Node{{ i-1 }}:</span>
                  <span>{{ state.detailDialog.data[`waveLength${i-1}`] !== undefined ? state.detailDialog.data[`waveLength${i-1}`] : '-' }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-descriptions-item>
        
        <!-- 温度数据 -->
        <el-descriptions-item label="温度数据" :span="2">
          <div style="max-height: 300px; overflow-y: auto;">
            <el-row :gutter="16" style="margin-top: 10px;">
              <el-col :span="12" v-for="i in 30" :key="`temp-${i-1}`">
                <div style="display: flex; justify-content: space-between; padding: 4px 0;">
                  <span>Node{{ i-1 }}:</span>
                  <span>{{ state.detailDialog.data[`tempValue${i-1}`] !== undefined ? state.detailDialog.data[`tempValue${i-1}`] : '-' }}</span>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-descriptions-item>
        
        <!-- 所有数据字段（JSON格式） -->
        <el-descriptions-item label="完整数据（JSON格式）" :span="2">
          <div style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 400px; overflow-y: auto;">
            <pre style="margin: 0; white-space: pre-wrap; font-size: 12px;">{{ JSON.stringify(state.detailDialog.data, null, 2) }}</pre>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElDialog, ElDescriptions, ElDescriptionsItem, ElRow, ElCol, ElTooltip, ElButton, ElDivider, ElPopconfirm } from 'element-plus'
import { View, Delete } from '@element-plus/icons-vue'
import { IColumn } from '@/components/common/types/tableCommon'
import YtCrud from '@/components/common/yt-crud.vue'
import { 
  getDeviceCollectionList, 
  exportDeviceCollection,
  IDeviceCollectionDataQuery,
  IDeviceCollectionDataVo
} from '../equipment/api/deviceCollectionDataHistory.api'

// 定义数据
const data = ref<IDeviceCollectionDataVo[]>([])
const crudRef = ref()

// 状态管理
const state = reactive({
  page: {
    pageSize: 10,
    pageNum: 1,
  },
  total: 0,
  loading: false,
  query: {} as IDeviceCollectionDataQuery,
  
  // 详情对话框
  detailDialog: {
    visible: false,
    title: '数据详情',
    data: null as IDeviceCollectionDataVo | null,
  },
})

// 定义表格列
const column = ref<IColumn[]>([
  {
    label: 'ID',
    key: 'id',
    search: false,
    tableWidth: 80,
  },
  {
    label: '租户ID',
    key: 'tenantId',
    search: false,
    tableWidth: 100,
    formHide: true,
  },
  {
    label: '采集时间',
    key: 'collectTime',
    tableWidth: 220,
    search: true,
    type: 'date',
    hide: true,
    formHide: true,
    componentProps: {
      type: 'datetimerange',
      valueFormat: 'timestamp',
      placeholder: ['开始时间', '结束时间'],
      format: 'YYYY-MM-DD HH:mm:ss',
      'value-format': 'YYYY-MM-DD HH:mm:ss',
      shortcuts: [
        {
          text: '最近1小时',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000)
            return [start.getTime(), end.getTime()]
          },
        },
        {
          text: '最近24小时',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 24 * 1000)
            return [start.getTime(), end.getTime()]
          },
        },
        {
          text: '最近7天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 24 * 7 * 1000)
            return [start.getTime(), end.getTime()]
          },
        },
        {
          text: '最近30天',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 24 * 30 * 1000)
            return [start.getTime(), end.getTime()]
          },
        },
      ],
    },
  },
  {
    label: '采集时间',
    key: 'collectDatetime',
    tableWidth: 220,
    slot: true,
    search: false,
    formHide: true,
  },
  {
    label: '通道索引',
    key: 'channelIndex',
    tableWidth: 100,
    search: false,
    formHide: true,
  },
  // 波长数据统计字段
  {
    label: '波长数据',
    key: 'waveLength0',
    tableWidth: 120,
    formHide: true,
  },
  
  // 温度数据统计字段
  {
    label: '温度数据',
    key: 'tempValue0',
    tableWidth: 120,
    formHide: true,
  },
])

// 格式化日期（包含毫秒）
const formatDateWithMilliseconds = (timestamp: number) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const formatted = date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
  const milliseconds = date.getMilliseconds().toString().padStart(3, '0')
  return `${formatted}.${milliseconds}`
}

// 格式化日期（不含毫秒，保留原函数）
const formatDate = (timestamp: number) => {
  if (!timestamp) return '-'
  return new Date(timestamp).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
  })
}

// 获取数据
const getData = () => {
  state.loading = true
  
  // 处理查询参数
  const queryParams = { ...state.query }
  
  // 处理采集时间范围查询
  if (queryParams.collectTime && Array.isArray(queryParams.collectTime)) {
    queryParams.startTime = queryParams.collectTime[0]
    queryParams.endTime = queryParams.collectTime[1]
    
    // 确保startTime和endTime是毫秒级时间戳
    if (typeof queryParams.startTime === 'string') {
      queryParams.startTime = new Date(queryParams.startTime).getTime()
    }
    if (typeof queryParams.endTime === 'string') {
      queryParams.endTime = new Date(queryParams.endTime).getTime()
    }
    
    delete queryParams.collectTime
  }
  
  // 清理空值
  Object.keys(queryParams).forEach(key => {
    if (queryParams[key] === '' || queryParams[key] === null || queryParams[key] === undefined) {
      delete queryParams[key]
    }
  })
  
  getDeviceCollectionList({
    ...state.page,
    ...queryParams,
  })
    .then((res) => {
      console.log('获取设备数据收集历史:', res)
      if (res != null) {
        data.value = res.rows || []
        state.total = res.total || 0
        
        // 添加调试信息，检查波长和温度数据
        if (data.value.length > 0) {
          console.log('第一条数据详情:', data.value[0])
          
          // 检查是否有波长数据字段
          const firstRow = data.value[0]
          console.log('波长数据字段检查:')
          for (let i = 0; i < 30; i++) {
            const waveKey = `waveLength${i}`
            console.log(`${waveKey}:`, firstRow[waveKey])
          }
          
          console.log('温度数据字段检查:')
          for (let i = 0; i < 30; i++) {
            const tempKey = `tempValue${i}`
            console.log(`${tempKey}:`, firstRow[tempKey])
          }
        }
      } else {
        ElMessage.error(res.message || '获取数据失败')
      }
    })
    .catch((error) => {
      console.error('获取设备数据收集历史失败:', error)
      ElMessage.error('获取数据失败')
    })
    .finally(() => {
      state.loading = false
    })
}

// 查看详情
const handleViewDetail = async (row: IDeviceCollectionDataVo) => {
  try {
    // 由于API中没有单独获取详情的接口，直接使用当前行数据
    state.detailDialog.data = row
    state.detailDialog.title = `数据详情 - ID: ${row.id}`
    state.detailDialog.visible = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除数据
const handleDel = async (row: any) => {
  ElMessage.warning('删除功能暂未实现')
}

// 导出数据
const handleExport = () => {
  exportDeviceCollection(state.query)
    .then((res) => {
      // 处理文件下载
      const blob = new Blob([res.data])
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `设备数据收集记录_${new Date().getTime()}.xlsx`
      link.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功!')
    })
    .catch((error) => {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    })
}

// 保存数据（新增/编辑）
const onSave = async ({ type, data: formData, cancel }: any) => {
  ElMessage.warning('保存功能暂未实现')
}

// 弹窗前置操作
const openBeforeFun = ({ type, data }: any) => {
  if (type === 'add') {
    // 新增时的默认值设置
    data.collectTime = Date.now()
    data.collectDatetime = new Date().toISOString()
  }
}

// 初始化加载数据
onMounted(() => {
  getData()
})
</script>

<style lang="scss" scoped>
::v-deep(.el-radio-button__inner) {
  padding: 8px;
}
::v-deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
  border: 1px solid #0070ffff;
  background: #0070ff1a;
  box-shadow: none;
  svg {
    path {
      fill: #0070ffff;
    }
  }
}
</style>
